package com.xds.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xds.common.utils.HttpUtils;
import com.xds.common.utils.R;
import com.xds.gulimall.auth.feign.MemberFeign;
import com.xds.common.vo.MemberResVo;
import com.xds.gulimall.auth.vo.SocialUse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : baixu
 * @date : 17:00 2021/12/16
 */
@Controller
@Slf4j
public class OAuth2Controller {
    @Autowired
    MemberFeign memberFeign;
    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam String code, HttpSession session) throws Exception {
        //根据code换取accestoken
        //登陆成功跳回首页
//        SocialUse socialUse=new SocialUse();
//        UserInfo userInfo = new UserInfo();
        Map<String,String> map=new HashMap<>();
        map.put("grant_type","authorization_code");
        map.put("client_id","8cdb431e39a047b883af7742dd7536e07d56fc8d001ea1729c5ea16812492e13");
        map.put("client_secret","08169de42778216375d10f138ef4c3a972bd4c16ed9a53a9122e6bc893cf9b8a");
        map.put("redirect_uri","http://auth.xiaowenplus.com/oauth2.0/gitee/success");
        map.put("code",code);
//        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), null, map);
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());
       if (response.getStatusLine().getStatusCode()==200){
           //获取到了accesstoken
           String json = EntityUtils.toString(response.getEntity());

            SocialUse socialUse = JSON.parseObject(json, SocialUse.class);
//
           //第一次登陆进来的用户 视为注册
           R r = memberFeign.oauthLogin(socialUse);
           if (r.getCode()==0){
               MemberResVo data = r.getData("data", new TypeReference<MemberResVo>() {
               });
               System.out.println("登陆成功：用户信息"+data);
               log.info("登陆成功,用户信息{}"+data);
               session.setAttribute("loginUser",data);
               return "redirect:http://xiaowenplus.com";
           }else {
               return "redirect:http://auth.xiaowenplus.com/login.html";
           }
       }else {
           return "redirect:http://auth.xiaowenplus.com/login.html";
       }

    }
}
